/**
 * Created by huanlai.whl on 2017/3/1.
 */
var TAG = "AudioPlayer";

/**
 * 歌曲列表的播放模式
 */
const PlayMode = {
    sequential: 'list', //顺序播放
    circle: 'recycle',  // 列表循环
    singleLoop: 'single', // 单曲循环
    random: 'random',  // 随机播放
};

/**
 *  音乐播放器播放状态
 */
const PlayStatus = {
    Idle:'Idle',
    CanPlay:'canplay',
    Playing:'Playing',
    Pause:'normal',
    Error:'error',
    Ended:'ended'
};

class AudioPlayer {
    constructor() {
        this.playMode = PlayMode.sequential;
        this.PlayMode = PlayMode;
        this.currentIndex = 0;
        this.lastPlayTime = -1;
        this.playStatus = PlayStatus.Idle;
        this.currentSong = undefined;
        this.creatAudio();
    }

    creatAudio(){
        this.audio = $(`<audio autoplay src=""></audio>`).get(0);
        document.body.appendChild(this.audio);
        this.bindEvent();
    }

    setDataSrc(data, index) {
        console.log("set data src index == " + index);
        this.dataList = data;
        if(index){
            this.currentIndex = index;
        } else {
            this.currentIndex = 0;
        }
        var song = data[this.currentIndex];
        this.randomArr = this.shuffle([].concat(this.dataList));
        this.play(song);
    }

    togglePlay() {
        if(!this.audio || this.playStatus == PlayStatus.Error
            || this.playStatus == PlayStatus.Ended
            || this.playStatus == PlayStatus.Idle){
            console.log(" state not correct， do nothing");
            return;
        }
        if (this.audio.paused) {
            this.audio.play();
        } else {
            this.audio.pause();
        }
    }

    play(song) {
        if (song && song.listenurl) {
            this.updateCurrentSong(song);
        } else {
            //TODO 这里可以采用这种方式回调获取详情
            //this.request.getSongDetail(song.id, (state, text) =>{
            //    if(state){
            //        var songDetail = JSON.parse(text);
            //        song.listenurl = songDetail.listenurl;
            //        song.lyrics = songDetail.lyrics;
            //        console.log(" song.lyrics ======== " + song.lyrics);
            //        this.updateCurrentSong(song);
            //    } else {
            //        TVUtil.Toast.show('获取音乐详情失败，自动播放下一首');
            //        this.autoPlayNext();
            //    }
            //});
        }
    }

    //切换歌曲，切换太快会导致播放器挂掉，所以设置5s的延时设置。
    //每次切歌都会生效，只是播放间隔为5s
    updateCurrentSong(song) {
        if(!this.currentSong || this.currentSong.id != song.id){
            this.currentSong = song;
            console.log("--------- updateSong --------",TAG);
            this._exeEventListeners({
                type:'updatesong',
                currentSong:this.currentSong
            });
        }
        var currentTime = new Date().getTime();
        console.log(" crrentTime === " + currentTime + " lastPlayTime == " + this.lastPlayTime);
        if(this.playTimer){
            clearTimeout(this.playTimer);
        }
        if(currentTime < this.lastPlayTime + 5000){
            this.playTimer = setTimeout(function(){
                this.updateCurrentSong(this.currentSong);
            }.bind(this), 1000);
            return;
        }
        this.lastPlayTime = currentTime;
        //TODO 这里可以采用歌曲获取播放链接方式，可能有鉴权方面的需求
        //this.audio.setAttribute("src", this.request.getPlayUrl(song));
        this.audio.setAttribute("src", song.listenurl);
    }

    getCurrentSong(){
        return this.currentSong;
    }

    stop() {
        this.audio.pause();
        this.audio.setAttribute("src", "");
    }

    bindEvent() {
        this._listeners = new Array();
        this._on(this.audio, 'canplay', (e) => {
            console.log('----------audio canplay----------',TAG);
            this.playStatus = PlayStatus.CanPlay;
            var duration = this.audio.duration;
            if(duration < 0){
                duration = 100;
            }
            this.currentSong.duration = duration;
            this.currentSong.durationStr = this.getTime(duration * 1000);
            this._exeEventListeners({
                type:'canplay',
                currentSong:this.currentSong
            });
        });

        this._on(this.audio, 'error', (e) => {
            this.playStatus = PlayStatus.Error;
            console.log('---------------play error!-----------' + JSON.stringify(e),TAG);
        });

        this._on(this.audio, 'playing', (e) => {
            this.playStatus = PlayStatus.Playing;
            console.log('---------------playing!-----------' + JSON.stringify(e),TAG);
        });

        this._on(this.audio, 'play', (e) => {
            this.playStatus = PlayStatus.Playing;
            console.log('---------------play -----------' + JSON.stringify(e),TAG);
            this._exeEventListeners({type:'play'});
        });

        this._on(this.audio, 'pause', (e) => {
            this.playStatus = PlayStatus.Pause;
            console.log('---------------pause-----------' + JSON.stringify(e),TAG);
            this._exeEventListeners({type:'pause'});
        });

        this._on(this.audio, 'timeupdate', (e) => {
            var currentTime = this.audio.currentTime;
            this.currentSong.currentTime = currentTime > 0 ? currentTime : 0;
            this._exeEventListeners({
                type:'timeupdate',
                currentSong:this.currentSong
            });
        });

        this._on(this.audio, 'ended', () => {
            this.playStatus = PlayStatus.Ended;
            console.log("--------- ended --------",TAG);
            this.autoPlayNext();
        });

    }

    isPlaying(){
        return this.playStatus == PlayStatus.Playing;
    }

    //供外面注册监听
    on(type, callBack){
        for (let i = 0, l = this._listeners.length; i < l; i++) {
            const listener = this._listeners[i];
            if (!listener) {
                this._listeners.splice(i,1,{
                    type:type,
                    callBack:callBack
                });
                return i;
            }
        }
        this._listeners.push({
            type:type,
            callBack:callBack
        });
        return this._listeners.length - 1;
    }

    //取消监听，入参为注册时返回的index
    off(index) {
        if (index < 0) {
            return;
        }
        this._listeners[index] = null;
    }

    getTime (milliseconds) {
        let seconds = Math.floor(milliseconds / 1000);
        let minutes = Math.floor(seconds / 60);
        seconds = seconds - (minutes * 60);
        return (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
    }

    //自动播放下一曲，需要根据播放模式确认
    autoPlayNext() {
        var nextIndex = this.currentIndex;
        var datalist = this.dataList;
        switch (this.playMode) {
            case PlayMode.singleLoop:
                break;

            case PlayMode.sequential:
                if(nextIndex >= datalist.length - 1){
                    this.stop();
                    return;
                }
                nextIndex++;
                break;

            case PlayMode.circle:
                nextIndex = nextIndex >= datalist.length - 1 ? 0 : nextIndex++;
                break;

            case PlayMode.random:
                datalist = this.randomArr;
                nextIndex = nextIndex >= datalist.length - 1 ? nextIndex++ : 0;
                break;
        }
        this.currentIndex = nextIndex;
        this.play(datalist[this.currentIndex]);
    }

    //手动播放下一曲，单曲循环也会播放下一曲
    playNext() {
        var nextIndex = this.currentIndex;
        var datalist = this.playMode == PlayMode.random ? this.randomArr : this.dataList;
        if(!datalist){
            return;
        }
        nextIndex = nextIndex >= (datalist.length - 1) ? 0 : (nextIndex + 1);
        this.currentIndex = nextIndex;
        this.play(datalist[this.currentIndex]);
    }

    //手动播放上一曲
    playLast() {
        var nextIndex = this.currentIndex;
        var datalist = this.playMode == PlayMode.random ? this.randomArr : this.dataList;
        if(!datalist){
            return;
        }
        nextIndex = nextIndex > 0 ? (nextIndex - 1) : (datalist.length - 1);
        this.currentIndex = nextIndex;
        this.play(datalist[this.currentIndex]);
    }

    //切换播放模式
    togglePlayMode() {
        if (this.playMode == PlayMode.circle) {
            this.playMode = PlayMode.random;
            this.reCorrectCurrentIndex(this.currentSong, this.randomArr);
        } else if (this.playMode == PlayMode.random) {
            this.playMode = PlayMode.sequential;
            this.reCorrectCurrentIndex(this.currentSong, this.dataList);
        } else if (this.playMode == PlayMode.sequential) {
            this.playMode = PlayMode.singleLoop;
        } else if (this.playMode == PlayMode.singleLoop) {
            this.playMode = PlayMode.circle;
        }
        return this.playMode;
    }

    //获取播放模式
    getPlayMode() {
        return this.playMode;
    }

    setPlayMode(playMode){
        if(playMode in PlayMode){
            this.playMode = playMode;
        }
    }

    /**
     * shuffles array in place
     */
    shuffle(a) {
        let j, x;
        for (let i = a.length; i; i--) {
            j = Math.floor(Math.random() * i);
            x = a[i - 1];
            a[i - 1] = a[j];
            a[j] = x;
        }
        return a;
    }

    //随机播放下标不一样，切换下标
    reCorrectCurrentIndex(song, arrayData) {
        if (!song || !arrayData) {
            console.log("reCorrectCurrentIndex song or arrayData is null, return");
            return;
        }
        for (var i = 0; i < arrayData.length; i++) {
            if (arrayData[i].id == song.id) {
                this.currentIndex = i;
                break;
            }
        }
    }


    // 执行自定义的事件监听
    _exeEventListeners(e) {
        e.type = e.type.toLowerCase();
        if(e.type != 'timeupdate')
            console.log("e.type == " + e.type + " this._listeners.length " + this._listeners.length);
        for (let i = 0, l = this._listeners.length; i < l; i++) {
            const listener = this._listeners[i];
            if (!listener) {
                continue;
            }
            if (listener.type === e.type) {
                listener.callBack(e);
            }
        }
    }

    //这是私有方法，请用上面的on方法注册监听
    _on(ele, type, fn) {
        ele.addEventListener ? ele.addEventListener(type, fn, false) :
            ele.attachEvent ? ele.attachEvent('on' + type, fn) :
                ele['on' + type] = fn;
    }

    _un(ele, type, fn) {
        ele.removeEventListener ? ele.removeEventListener(type, fn, false) :
            ele.detachEvent ? ele.detachEvent('on' + type.fn) :
                ele['on' + type] = null;
    }
}

export default AudioPlayer;
